#include <stdio.h>

#define MEM_SIZE 8096
#define BLOCK_SIZE 64

// 内存块结构
typedef struct Block {
    int size;
    struct Block* next;
} Block;

static char mem[MEM_SIZE]; // 内存空间
static Block* freeList = NULL; // 空闲内存块链表

// 初始化内存管理系统
void initMemory() {
    freeList = (Block*)mem;
    freeList->size = MEM_SIZE - sizeof(Block);
    freeList->next = NULL;
}

// 分配内存
void* umalloc(int size) {
    size = (size + 7) / 8 * 8; // 确保内存大小是8的倍数
    Block* prev = NULL;
    Block* current = freeList;
    while (current) {
        if (current->size >= size) {
            if (current->size > size + sizeof(Block)) {
                // 如果空闲块大小大于所需大小加上一个新块的大小，拆分块
                Block* newBlock = (Block*)((char*)current + size);
                newBlock->size = current->size - size - sizeof(Block);
                newBlock->next = current->next;
                current->size = size;
                current->next = newBlock;
            }
            if (prev) {
                prev->next = current->next;
            } else {
                freeList = current->next;
            }
            return (char*)current + sizeof(Block);
        }
        prev = current;
        current = current->next;
    }
    return NULL; // 无法分配内存
}

// 释放内存
void ufree(void* ptr) {
    if (ptr) {
        Block* block = (Block*)((char*)ptr - sizeof(Block));
        block->next = freeList;
        freeList = block;
    }
}

// 碎片整理
void umerge() {
    Block* prev = NULL;
    Block* current = freeList;
    while (current) {
        if (prev && (char*)prev + prev->size + sizeof(Block) == (char*)current) {
            prev->size += current->size + sizeof(Block);
            prev->next = current->next;
            current = prev;
        }
        prev = current;
        current = current->next;
    }
}

int main() {
    initMemory();

    void* p1 = umalloc(256);
    void* p2 = umalloc(512);
    void* p3 = umalloc(128);
    void* p4 = umalloc(1024);

    umerge(); // 碎片整理

    ufree(p2); // 释放内存块 p2

    umerge(); // 碎片整理

    void* p5 = umalloc(256);
 printf("Hello, World!");
    return 0;
}

